const conf = require('../conf')
const mysql = require('mysql')
const pool = mysql.createPool(conf.db);

module.exports = {
    query: function (sql, params = []) {
        return new Promise((resolve, reject) => {
            pool.getConnection((err, conn) => {
                if (err) {
                    return reject(err);
                } else {
                    conn.query(sql, params, (err, result) => {
                        if (err) {
                            reject(err)
                        }
                        resolve(result);
                        conn.release();
                    })
                }
            })
        })
    },

    //增加(表名,{"字段名":"数据"},条件'WHERE +条件')
    async add(tablename, data, where) {
        let fieldName = [];
        let dataName = [];
        for (let x in data) {
            fieldName.push(x);
            dataName.push("'"+data[x]+"'");
        }
        let sql = `INSERT INTO ${tablename}(${fieldName.join(',')}) VALUES (${dataName.join(",")}) ${where}`
        
        return await this.query(sql, dataName)
    },

    //删除(表名,条件'WHERE +条件')
    async del(tablename, where) {
        let sql = `DELETE FROM ${tablename} ${where}`
        return await this.query(sql, [])
    },

    //修改 (表名,{"字段名":"数据"},条件'WHERE +条件')
    async modify(tablename, data, where) {
        let fieldName = [];
        let dataName = [];
        for (let x in data) {
            fieldName.push(x);
            dataName.push(data[x])
        }
        
        let fieldArr = '';
        fieldName.forEach(item => {
            fieldArr += (fieldArr == '') ? `${item}=?` : `,${item}=?`
        })
        let sql = `UPDATE ${tablename} SET ${fieldArr} ${where}`
        return await this.query(sql, dataName)
    },

    //单条查询
    async singleSearch(tablename, fieldName, where) {
        let sql = `SELECT ${fieldName} FROM ${tablename} ${where}`;
        return await this.query(sql, [])
    },

    //多条查询
    async multipleSearch(tablename, fieldName, where, other = '', limit = '') {
        let fieldArr = [];
        for (let x in fieldName) {
            fieldArr.push(x)
        }
        let sql = `SELECT ${fieldName.join(',')} FROM ${tablename} ${where}${other}${limit}`
        return await this.query(sql, [])
    },

    //多表删除
    async moreDel(tablename, where) {
        let sql = `DELETE ${tablename} FROM ${tablename} ${where}`
        return await this.query(sql, [])
    },



}